import SockJS from 'sockjs-client'

class SimpleWebSocketService {
  constructor() {
    this.socket = null
    this.connected = false
    this.subscriptions = new Map()
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.messageQueue = []
  }

  connect() {
    return new Promise((resolve, reject) => {
      try {
        this.socket = new SockJS('/ws')
        
        this.socket.onopen = () => {
          console.log('WebSocket连接成功')
          this.connected = true
          this.reconnectAttempts = 0
          
          // 发送队列中的消息
          while (this.messageQueue.length > 0) {
            const message = this.messageQueue.shift()
            this.send(message.destination, message.data)
          }
          
          resolve()
        }
        
        this.socket.onmessage = (event) => {
          try {
            const message = JSON.parse(event.data)
            this.handleMessage(message)
          } catch (error) {
            console.error('解析WebSocket消息失败:', error)
          }
        }
        
        this.socket.onclose = (event) => {
          console.log('WebSocket连接关闭:', event)
          this.connected = false
          
          // 自动重连
          if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++
            console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`)
            setTimeout(() => {
              this.connect().catch(console.error)
            }, 3000)
          }
        }
        
        this.socket.onerror = (error) => {
          console.error('WebSocket连接错误:', error)
          this.connected = false
          reject(error)
        }
        
      } catch (error) {
        console.error('WebSocket初始化失败:', error)
        reject(error)
      }
    })
  }

  disconnect() {
    if (this.socket) {
      try {
        this.socket.close()
      } catch (error) {
        console.error('WebSocket断开连接失败:', error)
      }
      this.connected = false
      this.subscriptions.clear()
    }
  }

  subscribe(topic, callback) {
    if (!this.connected) {
      console.error('WebSocket未连接')
      return null
    }

    this.subscriptions.set(topic, callback)
    
    // 发送订阅消息
    this.send('/app/subscribe', { topic })
    
    return {
      unsubscribe: () => {
        this.subscriptions.delete(topic)
        this.send('/app/unsubscribe', { topic })
      }
    }
  }

  send(destination, data) {
    if (!this.connected) {
      // 如果未连接，将消息加入队列
      this.messageQueue.push({ destination, data })
      return false
    }

    try {
      const message = {
        destination,
        data,
        timestamp: new Date().toISOString()
      }
      this.socket.send(JSON.stringify(message))
      return true
    } catch (error) {
      console.error('发送WebSocket消息失败:', error)
      return false
    }
  }

  handleMessage(message) {
    const { type, data, timestamp } = message
    
    // 处理不同类型的消息
    switch (type) {
      case 'config':
        this.notifySubscribers('/topic/screen-config', { type, data, timestamp })
        break
      case 'switch':
        this.notifySubscribers('/topic/screen-switch', { type, data, timestamp })
        break
      case 'status':
        this.notifySubscribers('/topic/screen-status', { type, data, timestamp })
        break
      default:
        console.log('收到未知类型消息:', message)
    }
  }

  notifySubscribers(topic, message) {
    const callback = this.subscriptions.get(topic)
    if (callback) {
      callback(message)
    }
  }

  isConnected() {
    return this.connected
  }

  getConnectionStatus() {
    return {
      connected: this.connected,
      reconnectAttempts: this.reconnectAttempts,
      maxReconnectAttempts: this.maxReconnectAttempts
    }
  }
}

export default new SimpleWebSocketService() 